package com.legend.utils;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JLabel;

import org.apache.log4j.Logger;

import sun.font.Font2D;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import examples.nntp.newsgroups;
import freemarker.core._RegexBuiltins.replace_reBI;

/**
 * User: ChuanQi Date: 13-6-17 Time: 上午10:18 To change this template use File |
 * Settings | File Templates.
 */
@SuppressWarnings("restriction")
public class FileUtils {
	static Logger log = Logger.getRootLogger();

	/*
	 * 写文件
	 */
	public static void writeFile(String fileName, String content) throws UnsupportedEncodingException, FileNotFoundException {
		String folder = fileName.substring(0, fileName.lastIndexOf('/'));

		File file = new File(folder);
		if (!file.isDirectory()) {
			file.mkdirs();
		}
		if (!file.exists())
			try {
				file.mkdir();
				file.createNewFile();
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		FileOutputStream stream = new FileOutputStream(fileName);
		if (stream != null) {
			OutputStreamWriter streamWriter = null;
			streamWriter = new OutputStreamWriter(stream, "utf-8");

			BufferedWriter bw = new BufferedWriter(streamWriter);
			PrintWriter out = new PrintWriter(bw);
			out.write(content);
			out.close();
			try {
				stream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static void create() {

	}

	/**
	 * 添加图片水印
	 * 
	 * @param srcImg
	 *            目标图片路径，如：C:\\kutuku.jpg
	 * @param waterImg
	 *            水印图片路径，如：C:\\kutuku.png
	 * @param x
	 *            水印图片距离目标图片左侧的偏移量，如果x<0, 则在正中间
	 * @param y
	 *            水印图片距离目标图片上侧的偏移量，如果y<0, 则在正中间
	 * @param alpha
	 *            透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)
	 * @throws java.io.IOException
	 */
	public final static void addWaterMark(String srcImg, String waterImg, int x, int y, float alpha) throws IOException {
		// 加载目标图片
		File file = new File(srcImg);
		String ext = srcImg.substring(srcImg.lastIndexOf(".") + 1);
		Image image = ImageIO.read(file);
		int width = image.getWidth(null);
		int height = image.getHeight(null);

		// 将目标图片加载到内存。
		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bufferedImage.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);

		// 加载水印图片。
		Image waterImage = ImageIO.read(new File(waterImg));
		int width_1 = waterImage.getWidth(null);
		int height_1 = waterImage.getHeight(null);
		// 设置水印图片的透明度。
		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));

		// 设置水印图片的位置。
		int widthDiff = width - width_1;
		int heightDiff = height - height_1;
		if (x < 0) {
			x = widthDiff / 2;
		} else if (x > widthDiff) {
			x = widthDiff;
		}
		if (y < 0) {
			y = heightDiff / 2;
		} else if (y > heightDiff) {
			y = heightDiff;
		}

		// 将水印图片“画”在原有的图片的制定位置。
		g.drawImage(waterImage, x, y, width_1, height_1, null);
		// 关闭画笔。
		g.dispose();

		// 保存目标图片。
		ImageIO.write(bufferedImage, ext, file);
	}

	public enum WaterPos {
		center, leftTop, rightTop, leftBottom, rightBottom, topCenter, bottomCenter, leftCenter, RightCenter
	}

	private static int x = 0;
	private static int y = 0;

	/**
	 * 计算水印的位置
	 * 
	 * @param waterPos
	 *            水印在哪个位置
	 * @param sourceW
	 *            源图的宽
	 * @param sourceH
	 *            源图的高
	 * @param waterW
	 *            水印图的宽
	 * @param waterH
	 *            水印图的高
	 */
	private static void waterPosX(WaterPos waterPos, int sourceW, int sourceH, int waterW, int waterH) {

		switch (waterPos) {
		case leftCenter:
			x = 0;
			y = (sourceH - waterH) / 2;
			break;
		case RightCenter:
			x = sourceW - waterW;
			y = (sourceH - waterH) / 2;
			break;
		case topCenter:
			x = (sourceW - waterW) / 2;
			y = 0;
			break;
		case bottomCenter:
			x = (sourceW - waterW) / 2;
			y = sourceH - waterH;
			break;
		case leftBottom:
			x = 0;
			y = sourceH - waterH;
			break;
		case rightBottom:
			x = sourceW - waterW;
			y = sourceH - waterH;
			break;
		case center:
			x = (sourceW - waterW) / 2;
			y = (sourceH - waterH) / 2;
			break;
		case leftTop:
			x = 0;
			y = 0;
			break;
		case rightTop:
			x = sourceW - waterW;
			y = 0;
			break;
		default:
			x = sourceW - waterW;
			y = sourceH - waterH;
			break;
		}
	}

	/**
	 * 添加水印图片
	 * 
	 * @param sourceImg
	 *            源图全路径
	 * @param waterImg
	 *            水印全路径
	 * @param waterPos
	 *            水印位置
	 * @param alpha
	 *            透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)
	 * @throws java.io.IOException
	 */
	public static void addWaterMark(String sourceImg, String waterImg, WaterPos waterPos, float alpha) throws IOException {
		File file = new File(sourceImg);
		Image image = ImageIO.read(file);
		int height = image.getHeight(null);
		int width = image.getWidth(null);
		BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffer.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);
		File wFile = new File(waterImg);
		Image wImg = ImageIO.read(wFile);
		int wHeight = wImg.getHeight(null);
		int wWidth = wImg.getWidth(null);
		System.out.println(wWidth + ":" + wHeight);
		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
		waterPosX(waterPos, width, height, wWidth, wHeight);
		g.drawImage(wImg, x, y, wWidth, wHeight, null);
		g.dispose();
		String ext = sourceImg.substring(sourceImg.lastIndexOf(".") + 1);
		ImageIO.write(buffer, ext, file);
	}

	/**
	 * 加文字文印
	 * 
	 * @param sourceImg
	 *            源图全地址
	 * @param waterText
	 *            文印文字
	 * @param waterPos
	 *            水印位置
	 * @param color
	 *            文字颜色
	 * @param fontSize
	 *            文字大小
	 * @param fontStyle
	 *            文字样式
	 * @param fontName
	 *            字体名称
	 * @param alpha
	 *            透明度(0.0 -- 1.0, 0.0为完全透明，1.0为完全不透明)
	 * @throws java.io.IOException
	 */
	public static void addWaterMark(String sourceImg, String waterText, WaterPos waterPos, Color color, int fontSize, int fontStyle,
			String fontName, float alpha) throws IOException {
		File file = new File(sourceImg);
		Image image = ImageIO.read(file);
		int height = image.getHeight(null);
		int width = image.getWidth(null);
		BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffer.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);
		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.9f));
		int len = waterText.length() * fontSize;
		waterPosX(waterPos, width, height, len, fontSize / 2);
		g.setColor(color);
		g.setFont(new Font(fontName, fontStyle, fontSize));
		y = y < fontSize ? y + fontSize : y;
		g.drawString(waterText, x, y);
		g.dispose();
		String ext = sourceImg.substring(sourceImg.lastIndexOf(".") + 1);
		ImageIO.write(buffer, ext, file);
	}

	/**
	 * 把文字转为图片
	 * 
	 * @param text
	 *            要写的内容
	 * @throws java.io.IOException
	 */
	public static void textToImg(String text, int fontSize, HttpServletResponse response) throws IOException {
		Font font = new Font("楷体", Font2D.NATIVE_RANK, fontSize);
		FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
		int height = fm.getHeight();// 字的高度
		int width = fm.stringWidth(text);
		System.out.println(height);
		BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffer.createGraphics();
		g.setBackground(Color.RED);
		g.fillRect(0, 0, width, height);
		g.setFont(font);
		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 1));
		g.setColor(Color.BLUE);
		g.drawString(text, 0, height - fontSize / 5);
		g.dispose();
		// File file = new File("C://2.jpg");
		ImageIO.write(buffer, "jpg", response.getOutputStream());
	}

	public static int[] getStringWidth(String str) {
		JLabel label = new JLabel();
		FontMetrics metrics;
		int textH = 0;
		int textW = 0;
		label.setText(str);
		metrics = label.getFontMetrics(label.getFont());
		textH = metrics.getHeight();// 字符串的高, 只和字体有关
		textW = metrics.stringWidth(label.getText());// 字符串的宽
		int[] num = new int[2];
		num[0] = textH;
		num[1] = textW;
		return num;
	}

	/**
	 * 
	 * @param filename
	 *            原文件
	 * @param thumbWidth
	 *            输出宽高
	 * @param thumbHeight
	 *            输出高度
	 * @param quality
	 *            压缩质量
	 * @param outFilename
	 *            输出文件
	 * @throws InterruptedException
	 * @throws java.io.FileNotFoundException
	 * @throws java.io.IOException
	 */
	public static void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)
			throws InterruptedException, FileNotFoundException, IOException {
		// load image from filename
		Image image = Toolkit.getDefaultToolkit().getImage(filename);
		MediaTracker mediaTracker = new MediaTracker(new Container());
		mediaTracker.addImage(image, 0);
		mediaTracker.waitForID(0);
		// use this to test for errors at this point:
		// System.out.println(mediaTracker.isErrorAny());

		// determine thumbnail size from WIDTH and HEIGHT
		double thumbRatio = (double) thumbWidth / (double) thumbHeight;
		int imageWidth = image.getWidth(null);
		int imageHeight = image.getHeight(null);
		double imageRatio = (double) imageWidth / (double) imageHeight;
		if (thumbRatio < imageRatio) {
			thumbHeight = (int) (thumbWidth / imageRatio);
		} else {
			thumbWidth = (int) (thumbHeight * imageRatio);
		}

		// draw original image to thumbnail image object and
		// scale it to the new size on-the-fly
		BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2D = thumbImage.createGraphics();
		graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);

		// save thumbnail image to outFilename
		BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
		quality = Math.max(0, Math.min(quality, 100));
		param.setQuality((float) quality / 100.0f, false);
		encoder.setJPEGEncodeParam(param);
		encoder.encode(thumbImage);
		out.close();
	}

	/**
	 * 截屏,输出的文字名
	 * 
	 * @param fileName
	 * @throws Exception
	 */
	public static void captureScreen(String fileName) throws Exception {

		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Rectangle screenRectangle = new Rectangle(screenSize);
		Robot robot = new Robot();
		BufferedImage image = robot.createScreenCapture(screenRectangle);
		ImageIO.write(image, "png", new File(fileName));

	}

	/**
	 * 读取文件
	 * 
	 * @param filePath 文件绝对路径
	 * @return 文件内容
	 */
	public static String ReadFile(String filePath) {
		File file = new File(filePath);
		if (file.exists() && file.canRead()) {
			BufferedReader bReader = null;
			String line = null;
			StringBuffer buffer = new StringBuffer();
			try {
				bReader =new BufferedReader(new FileReader(file));
				while ((line = bReader.readLine())!=null) {
					buffer.append(line);
				}
				return buffer.toString();
			} catch (Exception e) {
				// TODO: handle exception
				log.error(e.getMessage());
			}
		}
		return "";
	}
    private static List<String> filelist = new ArrayList();
    private static  int count=0;
    public static List<String> refreshFileList(String strPath) {
        File dir = new File(strPath);
        File[] files = dir.listFiles();
        if (files == null)
            return filelist;
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                refreshFileList(files[i].getAbsolutePath());
            } else {
                String strFileName = files[i].getAbsolutePath().toLowerCase();
                count++;
                System.out.println(count+"---"+strFileName);
                filelist.add(strFileName);
            }
        }
        return filelist;
    }
	public static void main(String[] args) throws IOException {
        long a = System.currentTimeMillis();
        List<String> lst= refreshFileList("oa");
        System.out.println(lst.size() + "  总文件数" + filelist.size());
        System.out.println(System.currentTimeMillis() - a);
		// writeFile("test.txt", "hello see 加");
		// String waterImg =
		// "C:\\Users\\Public\\Pictures\\Sample Pictures\\water.jpg";
		// String sourceImg =
		// "C:\\Users\\Public\\Pictures\\Sample Pictures\\Tulips1.jpg";
		// addWaterMark(sourceImg, waterImg, WaterPos.rightBottom, 1.0f);
		// addWaterMark(sourceImg, "测试水印文字", WaterPos.bottomCenter, Color.red,
		// 30, Font2D.NATIVE_RANK, "草书", 0.5f);
		// textToImg("中国!",30);
		// int[] is=getStringWidth("中国好,香港好.香港好,中国好");
		// for (int i : is) {

		// }

	}
}
